import {parseCameraConfig,getVideoDevicesAndGenerateJSON,showNotification} from "./utils.js"
import {socket} from "./socket.js"
document.getElementById('generate-json-btn').addEventListener('click', async () => {
    try {
        await getVideoDevicesAndGenerateJSON();
        showNotification('设备信息已生成并下载为 camera_devices.json','success',5000);
    } catch (error) {
        alert(error);
    }
});
// 初始化上传功能
const configUploadBtn = document.getElementById('config-upload-btn');
// 用于获取ROOM号的map映射
export let cameraId2RoomId = null;
configUpload.addEventListener('change', async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    try {
        const config = await parseCameraConfig(file);
        console.log('解析后的配置:', config);
        // 这里可以添加应用配置的逻辑（例如更新各摄像头采样频率）
        showNotification('配置文件解析成功，共包含'+ config.cameras.length +'个摄像头配置','success',5000);
        configUploadBtn.disabled = false;
        configUploadBtn.classList.remove('bg-gray-300', 'text-gray-500', 'cursor-not-allowed');
        configUploadBtn.classList.add('bg-primary', 'hover:bg-primary/90', 'text-white', 'shadow-md', 'hover:shadow-lg');
    } catch (error) {
        showNotification(error,'danger',5000);
        e.target.value = ''; // 清空文件选择
        document.getElementById('upload-file-name').textContent = '选择JSON文件';
        document.getElementById('parse-json-btn').classList.add('disabled');
        document.getElementById('parse-json-btn').setAttribute('disabled', true);
    }
});

configUploadBtn.addEventListener('click',()=>{
    //获取文件
    const file = configUpload.files[0];
    const formData = new FormData();
    formData.append('config',file);
    console.log(formData);
    console.log(file);
    //closeCamera()
    //video_output_stop()
    fetch('/upload/config', {
        method: 'POST',
        body: formData
    })
   .then(response => response.json())
   .then(data => {
        console.log(data);
        if(data['success']){
            socket.emit('get_config');
        }
    })
   .catch(error => {
        console.error('上传配置失败:', error);
    });
    configUploadBtn.disabled = true;
    configUploadBtn.classList.remove('bg-primary', 'hover:bg-primary/90', 'text-white', 'shadow-md', 'hover:shadow-lg');
    configUploadBtn.classList.add('bg-gray-300', 'text-gray-500', 'cursor-not-allowed');

});
socket.emit('get_config');
socket.on('config',(data)=>{
    console.log(data);
    cameraId2RoomId = data;
    showNotification("获取并更新配置文件成功！",'success',3000);
})